package com.by_man.presenter.module_gestureLock;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.LoginActivity;
import com.by_man.presenter.R;
import com.by_man.presenter.menu_activity.SettingActivity;
import com.by_man.repository.IpAddress;
import com.by_man.repository.PostJsonArrayRequest;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by man on 2017-03-17.
 */
public class ModifyGestureLockVerifyActivity extends AppCompatActivity {
    private RequestQueue rQueue;
    private GestureLockViewGroup mGestureLockViewGroup;
    private int[] a;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_gesturelock_verify);
        rQueue = Volley.newRequestQueue(this);
        rQueue.start();
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, SettingActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, SettingActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }


    private void initView() {
        mGestureLockViewGroup = (GestureLockViewGroup) findViewById(R.id.id_gestureLockViewGroup);
        //依靠登录密码修改手势密码
        Button setting_forget_sscode=(Button)findViewById(R.id.forget_sscode);
        setting_forget_sscode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ModifyGestureLockVerifyActivity.this,LoginPasswordVerifyActivity.class);
                startActivity(intent);
            }
        });
        String answer = UserInfos.GestureLockAnswer;
        if (null == answer) {       // 服务器下载
            HashMap<String, String> params = new HashMap<>();
            params.put("token", UserInfos.token);
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest jsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST,
                    IpAddress.GestureLock, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArray) {
                            try {
                                JSONObject temp = (JSONObject) jsonArray.get(0);
                                UserInfos.GestureLockAnswer = temp.getString("gesture");
                                String gesture = temp.getString("gesture");
                                gesture.trim();
                                char[] c = gesture.toCharArray();
                                //String 转char[]型数组
                                String[] strArr = new String[c.length];
                                //char型数组转String型
                                for (int i = 0; i < c.length; i++) {
                                    strArr[i] = String.valueOf(c[i]);
                                }
                                //String型数组转int型数组
                                a = new int[strArr.length];
                                for (int i = 0; i < strArr.length; i++) {
                                    a[i] = Integer.parseInt(strArr[i]);
                                }

                                mGestureLockViewGroup.setAnswer(a);
                                mGestureLockViewGroup.setOnGestureLockViewListener(
                                        new GestureLockViewGroup.OnGestureLockViewListener() {
                                            /**
                                             * 错误超过五次控制
                                             */
                                            @Override
                                            public void onUnmatchedExceedBoundary() {
                                                Toast.makeText(ModifyGestureLockVerifyActivity.this, "错误3次,请您重新登录后修改手势密码",
                                                        Toast.LENGTH_SHORT).show();
                                                mGestureLockViewGroup.setUnMatchExceedBoundary(4);
                                                Intent intent = new Intent(ModifyGestureLockVerifyActivity.this, LoginActivity.class);
                                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                startActivity(intent);
                                            }

                                            /**
                                             *判断手势对错，可在下面控制intent
                                             */
                                            @Override
                                            public void onGestureEvent(boolean matched) {
                                                //   Toast.makeText(PassWord2.this, matched + "",Toast.LENGTH_SHORT).show();

                                                if (matched)   // 密码验证之后跳转
                                                {
                                                    mGestureLockViewGroup.reset();
                                                    Toast.makeText(ModifyGestureLockVerifyActivity.this, "手势密码正确，即将为您跳转！" + "",
                                                            Toast.LENGTH_SHORT).show();
                                                    Intent intent = new Intent(ModifyGestureLockVerifyActivity.this, ModifyGestureLockActivity.class);
                                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                                    startActivity(intent);

                                                } else {
                                                    Toast.makeText(ModifyGestureLockVerifyActivity.this, "手势密码错误", Toast.LENGTH_SHORT).show();
                                                    mGestureLockViewGroup.reset();
                                                }
                                            }

                                            @Override
                                            public void onBlockSelected(int[] c) {
                                            }
                                        }
                                );
                            } catch (JSONException je) {
                                je.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("ModifyGestureLockError", volleyError.getMessage(), volleyError);
                            Toast.makeText(ModifyGestureLockVerifyActivity.this, "请求手势密码失败!",Toast.LENGTH_SHORT).show();
                        }
                    });
            rQueue.add(jsonArrayRequest);
        } else {
            answer.trim();
            char[] c = answer.toCharArray();
            //String 转char[]型数组
            String[] strArr = new String[c.length];
            //char型数组转String型
            for (int i = 0; i < c.length; i++) {
                strArr[i] = String.valueOf(c[i]);
            }
            //String型数组转int型数组
            a = new int[strArr.length];
            for (int i = 0; i < strArr.length; i++) {
                a[i] = Integer.parseInt(strArr[i]);
            }

            mGestureLockViewGroup.setAnswer(a);
            mGestureLockViewGroup.setOnGestureLockViewListener(
                    new GestureLockViewGroup.OnGestureLockViewListener() {
                        /**
                         * 错误超过五次控制
                         */
                        @Override
                        public void onUnmatchedExceedBoundary() {
                            mGestureLockViewGroup.setUnMatchExceedBoundary(5);
                        }

                        /**
                         *判断手势对错，可在下面控制intent
                         */
                        @Override
                        public void onGestureEvent(boolean matched) {
                            //   Toast.makeText(PassWord2.this, matched + "",Toast.LENGTH_SHORT).show();

                            if (matched)   // 密码验证之后跳转
                            {
                                Toast.makeText(ModifyGestureLockVerifyActivity.this, "手势密码正确，即将为您跳转！" + "",
                                        Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(ModifyGestureLockVerifyActivity.this, ModifyGestureLockActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);

                            } else {
                                Toast.makeText(ModifyGestureLockVerifyActivity.this, "手势密码错误", Toast.LENGTH_SHORT).show();
                                mGestureLockViewGroup.reset();
                            }
                        }

                        @Override
                        public void onBlockSelected(int[] c) {
                        }
                    }
            );
        }
    }
}
